// 小心儿悠悠
import { Crypto, _ } from 'assets://js/lib/cat.js'

const FIXED_CONFIG = {
    host: 'http://cmsmytv.lyyytv.cn',
    cmskey: 'z0afJ9wfCMEuLwDMJCFHwFQmaxCzC5zM',
    RawPlayUrl: 0
};

const header = {
    'User-Agent': 'okhttp/3.12.11'
};

function lvdou(text) {
    try {
        const keyStr = FIXED_CONFIG.cmskey;
        const original_text = text;
        const url_prefix = "lvdou+";
        
        if (!original_text.startsWith(url_prefix)) {
            return original_text;
        }
        
        const ciphertext_b64 = original_text.substring(url_prefix.length);
        const key = Crypto.enc.Utf8.parse(keyStr.substring(0, 16));
        const iv = Crypto.enc.Utf8.parse(keyStr.substring(keyStr.length - 16));
        
        const decrypted = Crypto.AES.decrypt(ciphertext_b64, key, {
            iv: iv,
            mode: Crypto.mode.CBC,
            padding: Crypto.pad.Pkcs7
        });
        
        return decrypted.toString(Crypto.enc.Utf8);
    } catch (e) {
        return text;
    }
}

async function request(reqUrl, ua, timeout = 60000) {
    let res = await req(reqUrl, {
        method: 'get',
        headers: ua ? ua : {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36'},
        timeout: timeout,
    });
    return res.content;
}

async function home(filter) {
    try {
        let url = FIXED_CONFIG.host + "/api.php/app/nav?token=";
        const json = await request(url, header);
        const obj = JSON.parse(json);
        let jsonArray = obj.list || (obj.data && obj.data.list) || obj.data;
        const result = { class: [] };
        
        if (jsonArray != null) {
            for (let i = 0; i < jsonArray.length; i++) {
                const jObj = jsonArray[i];
                const typeName = jObj.type_name;
                const typeId = jObj.type_id;
                const newCls = {
                    type_id: typeId,
                    type_name: typeName,
                };
                const typeExtend = jObj.type_extend;
                if (filter) {
                    const filterArr = [];
                    if (typeExtend) {
                        for (let key in typeExtend) {
                            if (key === "class" || key === "area" || key === "lang" || key === "year") {
                                const jOne = {
                                    key: key,
                                    name: key === "class" ? "类型" : 
                                          key === "area" ? "地区" : 
                                          key === "lang" ? "语言" : "年份",
                                    value: [],
                                };
                                const values = typeExtend[key].split(',');
                                jOne.value.push({ n: "全部", v: "" });
                                for (let val of values) {
                                    jOne.value.push({ n: val, v: val });
                                }
                                filterArr.push(jOne);
                            }
                        }
                    }
                    filterArr.push({
                        key: "排序",
                        name: "排序",
                        value: [
                            { n: "最新", v: "time" },
                            { n: "最热", v: "hits" },
                            { n: "评分", v: "score" }
                        ]
                    });
                    if (!result.hasOwnProperty("filters")) {
                        result.filters = {};
                    }
                    result.filters[typeId] = filterArr;
                }
                result.class.push(newCls);
            }
        }
        return JSON.stringify(result);
    } catch (e) {
        return JSON.stringify({ class: [] });
    }
}

async function homeVod() {
    try {
        const url = FIXED_CONFIG.host + "/api.php/app/index_video?token=";
        const json = await request(url, header);
        const obj = JSON.parse(json);
        const videos = [];
        
        if (obj.list && Array.isArray(obj.list)) {
            for (let i = 0; i < obj.list.length; i++) {
                const section = obj.list[i];
                if (section.vlist && Array.isArray(section.vlist)) {
                    for (let j = 0; j < section.vlist.length; j++) {
                        const vObj = section.vlist[j];
                        videos.push({
                            vod_id: vObj.vod_id,
                            vod_name: vObj.vod_name,
                            vod_pic: vObj.vod_pic,
                            vod_remarks: vObj.vod_remarks || vObj.vod_time
                        });
                    }
                } else {
                    videos.push({
                        vod_id: section.vod_id,
                        vod_name: section.vod_name,
                        vod_pic: section.vod_pic,
                        vod_remarks: section.vod_remarks || section.vod_time
                    });
                }
            }
        }
        
        return JSON.stringify({ list: videos });
    } catch (e) {
        return JSON.stringify({ list: [] });
    }
}

async function category(tid, pg, filter, extend) {
    try {
        let url = `${FIXED_CONFIG.host}/api.php/app/video?tid=${tid}&class=${extend?.class||''}&area=${extend?.area||''}&lang=${extend?.lang||''}&year=${extend?.year||''}&by=${extend?.排序||'time'}&limit=18&pg=${pg}`;
        const json = await request(url, header);
        const obj = JSON.parse(json);
        const videos = [];
        const jsonArray = obj.list || (obj.data && obj.data.list) || obj.data;
        if (jsonArray) {
            for (let i = 0; i < jsonArray.length; i++) {
                const vObj = jsonArray[i];
                videos.push({
                    vod_id: vObj.vod_id,
                    vod_name: vObj.vod_name,
                    vod_pic: vObj.vod_pic,
                    vod_remarks: vObj.vod_remarks
                });
            }
        }
        return JSON.stringify({
            page: pg,
            pagecount: obj.pagecount || 1000,
            list: videos
        });
    } catch (e) {
        return JSON.stringify({
            page: pg,
            pagecount: 0,
            list: []
        });
    }
}

async function detail(ids) {
    try {
        const url = FIXED_CONFIG.host + "/api.php/app/video_detail?id=" + ids;
        const json = await request(url, header);
        const obj = JSON.parse(json);
        const data = obj.data || obj;
        const vod = {
            vod_id: data.vod_id || ids,
            vod_name: data.vod_name,
            vod_pic: data.vod_pic,
            vod_remarks: data.vod_remarks,
            vod_actor: data.vod_actor,
            vod_director: data.vod_director,
            vod_content: data.vod_content,
            vod_play_from: "",
            vod_play_url: ""
        };
        const playFrom = [];
        const playUrl = [];
        if (data.vod_url_with_player) {
            for (let item of data.vod_url_with_player) {
                let lineName = item.name || item.code || '';
                playFrom.push(lineName);
                
                let playUrlItem = item.url || '';
                
                if (playUrlItem.includes('#')) {
                    const urls = playUrlItem.split('#');
                    const decryptedUrls = [];
                    for (let url of urls) {
                        if (url) {
                            const parts = url.split('$', 2);
                            if (parts.length === 2) {
                                const decryptedPart = lvdou(parts[1]);
                                decryptedUrls.push(parts[0] + '$' + decryptedPart);
                            } else {
                                decryptedUrls.push(url);
                            }
                        }
                    }
                    playUrlItem = decryptedUrls.join('#');
                } else {
                    playUrlItem = lvdou(playUrlItem);
                }
                
                playUrl.push(playUrlItem);
            }
        }
        vod.vod_play_from = playFrom.join("$$$");
        vod.vod_play_url = playUrl.join("$$$");
        return JSON.stringify({ list: [vod] });
    } catch (e) {
        return JSON.stringify({ list: [] });
    }
}

function checkPlayUrl(content) {
    const pattern = /https?:\/\/.*(?:\.(?:avi|wmv|wmp|wm|asf|mpg|mpeg|mpe|m1v|m2v|mpv2|mp2v|ts|tp|tpr|trp|vob|ifo|ogm|ogv|mp4|m4v|m4p|m4b|3gp|3gpp|3g2|3gp2|mkv|rm|ram|rmvb|rpm|flv|mov|qt|nsv|dpg|m2ts|m2t|mts|dvr-ms|k3g|skm|evo|nsr|amv|divx|webm|wtv|f4v|mxf)|[\w\-_]+\.lyyytv\.cn\/.)/i;
    return pattern.test(content);
}

async function getRawUrl(original_url) {
    try {
        const response = await req(original_url, {
            method: 'get',
            headers: header,
            timeout: 20000,
            redirect: 'manual'
        });
        
        if (response.status >= 300 && response.status < 400) {
            const redirect_location = response.headers['Location'] || response.headers['location'];
            if (redirect_location) {
                if (redirect_location.startsWith('http')) {
                    return redirect_location;
                } else {
                    const baseUrl = original_url.split('/').slice(0, 3).join('/');
                    return baseUrl + redirect_location;
                }
            }
        }
        return original_url;
    } catch (e) {
        return original_url;
    }
}

async function play(flag, id, vipFlags) {
    try {
        let finalUrl = id;
        let jx = 0;
        
        if (checkPlayUrl(id)) {
            if (FIXED_CONFIG.RawPlayUrl === 1) {
                finalUrl = await getRawUrl(id);
            }
        } else if (/(?:www\.iqiyi|v\.qq|v\.youku|www\.mgtv|www\.bilibili)\.com/.test(id)) {
            jx = 1;
        }
        
        return JSON.stringify({
            jx: jx,
            playUrl: '',
            parse: 0,
            url: finalUrl,
            header: header
        });
        
    } catch (e) {
        return JSON.stringify({
            jx: 0,
            playUrl: '',
            parse: 0,
            url: id
        });
    }
}

async function search(key, quick) {
    try {
        const url = FIXED_CONFIG.host + "/api.php/app/search?text=" + encodeURIComponent(key) + "&pg=1";
        const json = await request(url, header);
        const obj = JSON.parse(json);
        const jsonArray = obj.list || (obj.data && obj.data.list) || obj.data;
        const videos = [];
        if (jsonArray) {
            for (let i = 0; i < jsonArray.length; i++) {
                const vObj = jsonArray[i];
                videos.push({
                    vod_id: vObj.vod_id,
                    vod_name: vObj.vod_name,
                    vod_pic: vObj.vod_pic,
                    vod_remarks:vObj.vod_remarks
                });
            }
        }
        return JSON.stringify({ list: videos });
    } catch (error) {
        return JSON.stringify({ list: [] });
    }
}

export function __jsEvalReturn() {
    return {
        home: home,
        homeVod: homeVod,
        category: category,
        detail: detail,
        play: play,
        search: search,
    };
}
